const fs = require("fs");
const path = require("path");
const sql = require("../../mysql");

module.exports = async ctx => {
  try {
    const file = ctx.request.files.file;
    const parentId = ctx.request.body.parentId;

    let imagePath = file.path;

    const reader = fs.createReadStream(imagePath);

    var myDate = new Date();
    var newFilename =
      myDate.getTime() +
      parseInt(Math.random() * 10000) +
      "." +
      file.name.split(".")[1];

    var targetPath =
      path.join(__dirname, "../../public/user-files") + `/${newFilename}`;

    const upStream = await fs.createWriteStream(targetPath);

    await reader.pipe(upStream);
    fs.unlink(imagePath + "." + file.name.split(".")[1], () => {});

    const staticPath = `/user-files/${newFilename}`;

    let realFile = await sql.Rfile.create({
      size: file.size,
      type: file.type,
      path: staticPath
    });

    let virtualFile = await sql.Vfile.create({
      name: file.name,
      isFolder: false,
      userId: ctx.request.userId,
      rfileId: realFile.id,
      parentId: parentId === "null" ? null : parentId
    });

    let newFile = {
      size: realFile.size,
      type: realFile.type,
      path: realFile.path,
      id: virtualFile.id,
      isFolder: virtualFile.isFolder,
      name: virtualFile.name,
      createdAt: virtualFile.createdAt,
      updatedAt: virtualFile.updatedAt,
      parentId
    };

    ctx.body = {
      code: 0,
      data: newFile
    };
  } catch (error) {
    console.log(error);

    ctx.response.status = 200;
    ctx.body = {
      code: -1,
      msg: error
    };
  }
};
